package ar.com.sectorwine.services;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ar.com.sectorwine.dao.EmpresasDAO;
import ar.com.sectorwine.dao.StocksDAO;
import ar.com.sectorwine.entities.Empresa;
import ar.com.sectorwine.entities.Stock;

@Service
@Transactional(propagation = Propagation.MANDATORY)
public class StockServiceImpl implements StockService {

	@Autowired
	StocksDAO stocksDAO;
	@Autowired
	EmpresasDAO empresasDAO;
	@Autowired
	ParametrosService parametrosService;

	private static final Logger logger = LoggerFactory
			.getLogger(StockServiceImpl.class);

	@Override
	public void crearStock(Long idEmpresa, Stock stock) {
		stock.setFechaCreacionStock(new Date());
		Empresa empresa = empresasDAO.findOne(idEmpresa);
		empresa.addStock(stock);

		empresasDAO.update(empresa);
		logger.info("STOCK CREADO");
	}

	@Override
	public List<Stock> getStocks() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Stock getStock(String id) {
		Long idStock = Long.parseLong(id);
		Stock stock = stocksDAO.findOne(idStock);
		logger.info("STOCK ENCONTRADO");
		return stock;
	}

	@Override
	public void modificarStock(Stock stock) {
		Stock stockOld = stocksDAO.findOne(stock.getId());
		
		stockOld.setAcidez(stock.getAcidez());
		stockOld.setAlcohol(stock.getAlcohol());
		stockOld.setAzucar(stock.getAzucar());
		stockOld.setCantidad(stock.getCantidad());
		stockOld.setColor(stock.getColor());
		stockOld.setEdad(stock.getEdad());
		stockOld.setIdINV(stock.getIdINV());
		stockOld.setMaceracion(stock.getMaceracion());
		stockOld.setPrecio(stock.getPrecio());
		stockOld.setVariedad(stock.getVariedad());
		stockOld.setVencimiento(stock.getVencimiento());
		
		stocksDAO.update(stockOld);
		logger.info("STOCK MODIFICADO");
		
	}

	@Override
	public boolean bajaStock(String id) {
		try {
			Long idStock = Long.parseLong(id);
			Stock stockMod = stocksDAO.findOne(idStock);
			stockMod.setBaja(true);
			stocksDAO.update(stockMod);
			logger.info("STOCK DADO DE BAJA");
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public Object getParametro(String parametroBuscado) {
		
		return parametrosService.getValue(parametroBuscado);			
		
	}

	@Override
	public List<Stock> buscarStockEmpresa(Long id) {
		Empresa empresa = empresasDAO.findOne(id);
		List<Stock> lista = empresa.getProductos();
		return lista;
	}

}
